//
//  WBMainTabBarController.swift
//  daoge_sineweibo
//
//  Created by 伍禄林 on 16/9/26.
//  Copyright © 2016年 伍禄林. All rights reserved.
//

import UIKit
import SVProgressHUD

class WBMainTabBarController: UITabBarController {
    
    lazy var compseBtn: UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
    
    var timer: Timer?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupNewFeatureViews()

        setupChildControllers()
        setupComposeBtn()
        //setupTimer()
        
        NotificationCenter.default.addObserver(self, selector: #selector(userLogin), name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
        
        delegate = self
        
        
    }
    
    @objc private func userLogin(n: Notification) {
        
        print("用户登陆通知＝＝＝＝＝＝\(n)")
        
        var when = DispatchTime.now()
        
        if n.object != nil {
            
            SVProgressHUD.setDefaultMaskType(.gradient)
            
            SVProgressHUD.showInfo(withStatus: "token过期，需要重新登陆")
            
            when = DispatchTime.now() + 2
        }
        
        DispatchQueue.main.asyncAfter(deadline: when) {
            
            SVProgressHUD.setDefaultMaskType(.clear)
            
            let nav = UINavigationController(rootViewController: WBOauthViewController())
            
            self.present(nav, animated: true, completion: nil)

            
        }
        
        
    }
    
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        
        return .portrait
    }
    
    deinit {
       
        timer?.invalidate()
        
        NotificationCenter.default.removeObserver(self)
    }
}
//设置新特性
extension WBMainTabBarController {
   
    func setupNewFeatureViews()  {
        //
        
        let v = isNewVersion ? WBNewFeatureView.newFeatureView() : WBWelcomeView.welcomeView();
        
        v.frame = view.bounds
        
        view.addSubview(v)
        
    }
    //新版本判断
    private var isNewVersion: Bool {
        
        
        
        let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
        
//        print(version)
//        
//        let path: String = ("version" as NSString).cz_appendDocumentDir()
//        
//        print(path)
//
//        let sandboxVersion = (try? String(contentsOfFile: path)) ?? ""
//        print(sandboxVersion)
//        
//        _ = try? version.write(toFile: path, atomically: true, encoding: .utf8)
        
        
        let defaults =  UserDefaults.standard
        
        let sandboxVersion = defaults.object(forKey: "version") as? String ?? ""
        
        defaults.set(version, forKey: "version")
        
        defaults.synchronize()
        
        return version != sandboxVersion
        
    }
}


extension WBMainTabBarController: UITabBarControllerDelegate {
    
    /// 点击tabBarItem 将要显示控制器的回调
    ///
    /// - parameter tabBarController:
    /// - parameter viewController:   将要显示的控制器
    ///
    /// - returns: <#return value description#>
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        
        let idx = (childViewControllers as NSArray).index(of: viewController)
        
        if selectedIndex == 0 && idx == selectedIndex {
            
            let navi = childViewControllers[0] as! UINavigationController
            
            let vc = navi.childViewControllers[0] as! WBHomeViewController
            
            vc.tableView?.setContentOffset(CGPoint(x: 0, y: -64), animated: true)
            
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: { 
                
                vc.loadData()
            })
            
        }
        
        return !viewController.isMember(of: UIViewController.self)
    }
    
}
extension WBMainTabBarController {
    
    
    func setupTimer() {
        
        timer = Timer.scheduledTimer(timeInterval: 60.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
        
    }
    
    @objc private func updateTimer() {
        
        if !WBNetworkingManager.shared.userLogon {
            return
        }
        
        WBNetworkingManager.shared.unreadCount { (count) in
        
            self.tabBar.items?[0].badgeValue = count > 0 ? "\(count)" : nil
            
            //8.0 之后  需要用户授权才能显示
            UIApplication.shared.applicationIconBadgeNumber = count
        }
    }
    
}


extension WBMainTabBarController {
    
    func setupComposeBtn() {
        
        tabBar.addSubview(compseBtn)
        let count = CGFloat(childViewControllers.count)
        let w = view.bounds.width / count
        
        compseBtn.frame = tabBar.bounds.insetBy(dx: 2 * w, dy: 0)
        compseBtn.addTarget(self, action: #selector(composeBtnClick), for: .touchUpInside)
    }
    
    @objc private func composeBtnClick()  {
        print("写微博")
        
        let v = WBComposeTypeView.composeTypeView()
        
        v.show {[weak v] (clsName) in
    
            guard let clsName = clsName,
            let cls = NSClassFromString(Bundle.main.title + "." + clsName ) as? UIViewController.Type else {
                v?.removeFromSuperview()
                return
            }
            
            let vc = cls.init()
            
            let nav = UINavigationController(rootViewController: vc)
            
            self.present(nav, animated: true, completion: { 
                v?.removeFromSuperview()
            })
        }
        
    }
    
    func setupChildControllers() {
        
        guard let path = Bundle.main.path(forResource: "main.json", ofType: nil),
              let data = NSData(contentsOfFile: path),
                let array = try?JSONSerialization.jsonObject(with: data as Data, options: []) as? [[String: Any]]
            else {
            
            return
        }
        
        
        var arrayM = [UIViewController]()
        for dict in array! {
        
            let vc =  controller(dict: dict)
            arrayM.append(vc)
            
        }
        viewControllers = arrayM
    }
    
    private func controller(dict: [String: Any]) -> UIViewController {
        
        guard let clsName = dict["clsName"] as? String,
            let title = dict["title"] as? String,
            let imageName = dict["imageName"] as? String,
            let cls = NSClassFromString(Bundle.main.title + "." + clsName) as? WBBaseViewController.Type,
            let visitorInfo = dict["visitorInfo"] as? [String: String]
            else {
                
            return UIViewController()
        }
        
        let vc = cls.init()
        vc.visitroInfo = visitorInfo
        vc.title = title
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.orange], for: .highlighted)
        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 14)], for: .normal)
        
        let nav = WBNaviViewController(rootViewController: vc)
        
        return nav
    }
    
}


